package com.hqbzl.chat.handler;

import com.hqbzl.chat.constant.Constants;
import com.hqbzl.chat.message.RpcRequestMessage;
import com.hqbzl.chat.message.RpcResponseMessage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@ChannelHandler.Sharable
@Slf4j
public class RpcResponseHandler extends SimpleChannelInboundHandler<RpcResponseMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcResponseMessage rpc) throws Exception {
        final int sequenceId = rpc.getSequenceId();
//        Constants.PROMISE_MAP.put(sequenceId, )
        log.debug("RpcResponseHandler==========================================>{}", rpc);
        //final Promise<Object> promise = Constants.PROMISE_MAP.get(rpc.getSequenceId());
        final Promise<Object> promise = Constants.PROMISE_MAP.remove(rpc.getSequenceId());
        if (promise == null) {
            throw new RuntimeException("RpcResponseHandler exception");
        }
        final Object object = rpc.getObject();
        final Exception exception = rpc.getException();
        if (exception != null) {
            promise.setFailure(exception);
        } else {
            promise.setSuccess(object);
        }
    }
}
